import { readJson, writeJSON } from '../util/PromiseJson.js'
import path from 'path'
import __dirname from '../util/dirname.js'
import fs from 'fs'
import { promisify } from 'util'

const readdir = promisify(fs.readdir)

const database = path.resolve(__dirname, '../data/people/peoples.json')
const avatar_template = 'http://127.0.0.1:9600/assets/images/people/{$}'

const getPersonByPage = async (req, res) => {
  const { page, size ,search} = req.query
  let peoples = await readJson(database)

  if(search){
    peoples = peoples.filter(e=>e.name.includes(search))
  }

  const start = (page - 1) * size
  let end = start + size
  end = end >= peoples.length ? peoples.length : end
  const sub = peoples.slice(start, end)
  sub.forEach(e => {
    e.avatar = avatar_template.replace('{$}', e.avatar)
  })

  res.send({ code: 200, msg: 'ok', data: sub, total: peoples.length, next: parseInt(page) + 1 })
}

const avatar_dir = path.resolve(__dirname,'../assets/images/people')

let avatar_list = []

async function updateAllAvatar(){
  const list = await readdir(avatar_dir)
  avatar_list = list
  avatar_list = avatar_list.map((av,i)=>{
    return {
      src:avatar_template.replace('{$}',av),
      id:i
    }
  })
}

const getAllPeopleAvatar = async (req,res)=>{
  await updateAllAvatar()
  res.send({
    code:200,
    msg:'ok',
    data:avatar_list
  })
}

export { getPersonByPage,getAllPeopleAvatar }
